#pragma once
#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "../CommonModule/comm.hpp"

class TcpServerSocket
{
    static const int defaultbacklog = 32;
public:
    TcpServerSocket() {}

    void Init(uint16_t port)
    {
        _listensock = socket(AF_INET, SOCK_STREAM, 0);

        int opt = 1;
        setsockopt(_listensock, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt));

        if (_listensock < 0)
        {
            ELOG("create listen sock failed");
            exit(Listensock_Error);
        }

        struct sockaddr_in addr;
        addr.sin_family = AF_INET;
        addr.sin_addr.s_addr = INADDR_ANY;
        addr.sin_port = htons(port);
        int n = bind(_listensock, (struct sockaddr *)(&addr), sizeof(addr));
        if (n < 0)
        {
            ELOG("bind listen sock failed");
            exit(Bind_Error);
        }

        n = listen(_listensock, defaultbacklog);
        if(n < 0)
        {
            ELOG("listen failed");
            exit(Listen_Error);
        }
    }

    int GetFd()
    {
        return _listensock;
    }

    void Close()
    {
        if (_listensock > 0)
            ::close(_listensock);
    }

    ~TcpServerSocket() {}

private:
    int _listensock = -1;
};